package com.enjia.common.framework;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.enjia.common.utils.CommonUtils;
import com.enjia.common.utils.LogUtils;
import com.enjia.common.utils.ViewFinder;
import com.enjia.common.view.CustomProgressDialog;
import com.enjia.common.view.TitleBarView;
import com.enjia.enjiashop.MyApplication;
import com.enjia.enjiashop.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.FormBody;

/**
 * Created by 陈飞飞 on 2017/5/5.
 */

public abstract class BaseFragment extends Fragment implements BaseViewInterface{

    protected Context mContext;
    //Fragment导航接口
    private FragmentNavInterface navInterface;

    protected BaseFragmentActivity mBaceFragmentActivity;
    //主内容视图
    private View mcontentView;
    //状态栏视图
    private View base_layout_statusBar;

    //空数据页面
    private View empty_view;
    private ImageView empty_img;
    private TextView empty_show_message;
    private Button empty_load_btn;

    private FrameLayout containerView;

    private ViewFinder viewFinder;
    //公共提示框
    Dialog prompt_dialog;
    //缓冲Dialog的调用
    private CustomProgressDialog cusProgressDialog;

    private Unbinder unbinder;

    // 公共的请求体
    protected FormBody.Builder formBody = new FormBody.Builder();

    // 导航栏
    private TextView tv_right;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=getActivity();
        mBaceFragmentActivity= (BaseFragmentActivity) getActivity();
        navInterface=mBaceFragmentActivity.getFragmentNavInterface();
        //添加公共请求体
        addFormBody();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        mcontentView = inflater.inflate(R.layout.fragment_base, null);
        viewFinder = new ViewFinder(mcontentView);
        containerView = (FrameLayout) viewFinder.find(R.id.baseFragmentContent);
        initBaseStateBar();
        initTitle();
        initEmpeyView();
        containerView.removeAllViews();
        View contentView = onCreateView(inflater);
        if (contentView != null) {
            containerView.addView(contentView);
        }
        unbinder = ButterKnife.bind(this, mcontentView);
        initView();
        initData();
        setListener();
        return mcontentView;
    }

    /**
     *  添加公共的信息
     */
    private void addFormBody() {
        formBody.add("version", CommonUtils.getAppVersion(getActivity()));
        formBody.add("os","android");
        formBody.add("channel","");

    }
    protected abstract View onCreateView(LayoutInflater mInflater);
    //初始化标题头
    private void initTitle(){
        ViewGroup viewGroup=viewFinder.find(R.id.baseFragmentTitleView);
        if (hasTitleHeader()) {
            viewGroup.setVisibility(View.VISIBLE);
            viewGroup.removeAllViews();
            viewGroup.addView(getTitleBarView());
        } else {
            viewGroup.setVisibility(View.GONE);
        }
    }

    /**
     * 状态栏控制
     */
    private void initBaseStateBar(){
        base_layout_statusBar = viewFinder.find(R.id.base_layout_statusBar);
        int statusBarHeight = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = this.getResources().getDimensionPixelSize(resourceId);
        }
        ViewGroup.LayoutParams layoutParams = base_layout_statusBar.getLayoutParams();
        layoutParams.height = statusBarHeight;
        base_layout_statusBar.setLayoutParams(layoutParams);

    }
    //初始化空页面
    private void initEmpeyView(){
        empty_view = viewFinder.find(R.id.empty_view);
        empty_img = viewFinder.find(R.id.empty_img);
        empty_show_message = viewFinder.find(R.id.empty_show_message);
        empty_load_btn = viewFinder.find(R.id.empty_load_btn);
    }

    protected boolean hasTitleHeader() {
        return true;
    }

    /**
     *
     * @return
     */
    protected View getTitleBarView() {
        View view = new TitleBarView()
                .build(mContext, R.layout.view_title_header)
                .bindOnClick(R.id.title_base_left, new View.OnClickListener() {
                    @Override
                   public void onClick(View v) {
                        clickTitleBarLeft();
                    }
                })
                .setTextView(R.id.title_base_center, getTitleValue())
                .create();
        //此处为防止事件穿透
        view.setClickable(true);
        if (isHideTitleLeftView()) {
            LinearLayout left = (LinearLayout) view.findViewById(R.id.title_base_left);
            left.setVisibility(View.GONE);
        }
        if (!isHideTitleRightBar()) {
            tv_right = (TextView) view.findViewById(R.id.title_base_right);
            tv_right.setVisibility(View.VISIBLE);
            tv_right.setText(getTitleRightValue());
            tv_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickTitleRight();
                }
            });
        }
        return view;
    }

    public void jumpToFragment(BaseFragment fragment) {
        navInterface.replaceFragment(fragment);
    }

    public void jumpToFragment(BaseFragment fragment, boolean isReplace) {
        navInterface.replaceFragment(fragment, isReplace);
    }

    /**
     * 标题头部返回按钮
     */
    public void goBack(){
        LogUtils.e("这是公共的======");
        navInterface.goBack();
    }

    /**
     * 设置 界面标题
     *
     * @return
     */
    protected abstract String getTitleValue();

    /**
     *  默认显示标题栏左侧返回图标
     */
    protected boolean isHideTitleLeftView() {
        return false;
    }

    public void onBack(){}

    /**
     *  home页的TitleBar的左边点击事件。
     */
    public void clickTitleBarLeft(){
        navInterface.goBack();
    }

    /**
     *隐藏某组件
     * @param view
     */
    public void setHideView(View view){
        if(View.VISIBLE == view.getVisibility()){
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 显示缓冲Dialog
     */
    public void showProgressDialog(Context mContext,String message){
        if(null==cusProgressDialog){
            cusProgressDialog=new CustomProgressDialog(mContext,message);
        }
        if(cusProgressDialog!=null){
            cusProgressDialog.show();
        }
    }

    /**
     * 控制状态栏的显示隐藏和颜色设置
     */
    public void setStatusBar(boolean isShow,int resourceColor){
        if(isShow) {
            base_layout_statusBar.setBackground(this.getResources().getDrawable(resourceColor));
        }
        else{
            base_layout_statusBar.setVisibility(View.GONE);
        }
    }
    /**
     * 销毁缓冲Dialog
     */
    public void destoryProgressDialog(){
        if(null != cusProgressDialog && cusProgressDialog.isShowing()){
            cusProgressDialog.dismiss();
            cusProgressDialog = null;
        }
    }

    //提示信息Dialog
    public void showPromiteDialog(String message, String leftContent, String rightContent, View.OnClickListener listener){
        final View prompt_view = LayoutInflater.from(mContext).inflate(R.layout.dialog_base_error,null);
        prompt_dialog = new AlertDialog.Builder(getActivity(),R.style.PaiLeDialog).create();
        prompt_dialog.show();
        prompt_dialog.setContentView(prompt_view);

        Button btn_right = (Button) prompt_view.findViewById(R.id.btn_right);
        Button btn_left = (Button) prompt_view.findViewById(R.id.btn_left);

        TextView dialog_prompt_message = (TextView) prompt_view.findViewById(R.id.dialog_prompt_message);
        dialog_prompt_message.setText(message);
        btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                prompt_dialog.dismiss();
            }
        });
        btn_right.setOnClickListener(listener);

        CommonUtils.setDialogSize(MyApplication.context,prompt_dialog,0.8);

    }

    protected static int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    /**
     *  是否隐藏statusBarView。
     */
    protected boolean isHideStatusView(){
        return false;
    }

    /**
     *  resourceId : 图片资源ID
     *  showString : 图片下面的文字
     *  showButtonFlag : 按钮是否显示
     *  strButonText : 按钮的文字
     *  clickListener : 按钮的监听事件
     */
    protected void showEmpty(int resourceId, String showString, String strButtonText, View.OnClickListener clickListener) {
        containerView.setVisibility(View.GONE);
        show(true, resourceId, showString, strButtonText, clickListener);
    }

    /**
     * 刷新页面，用于空页面后的正常页面展示
     */
    protected void refreshView(){
        containerView.setVisibility(View.VISIBLE);
        empty_view.setVisibility(View.GONE);
    }


    protected void show(boolean showImageFlag, int resourceId, String showString,String strButtonText, View.OnClickListener clickListener) {

        if (getActivity() == null) {
            return;
        }
        if(empty_view != null){
            empty_view.setVisibility(View.VISIBLE);
        }

        if(empty_img != null){
            if(showImageFlag){
                empty_img.setVisibility(View.VISIBLE);
                if (getActivity() != null) {
                    empty_img.setImageDrawable(getActivity().getResources().getDrawable(resourceId));
                } else {
                    empty_img.setImageDrawable(MyApplication.context.getResources().getDrawable(resourceId));
                }
            } else {
                empty_img.setVisibility(View.GONE);
            }
        }

        if(empty_show_message != null){
            empty_show_message.setVisibility(View.VISIBLE);
            if(!TextUtils.isEmpty(showString)){
                empty_show_message.setText(showString);
            } else {
                empty_show_message.setText("");
            }
        }

        if(empty_load_btn != null){
            if (null == strButtonText) {
                empty_load_btn.setVisibility(View.GONE);
            } else {
                empty_load_btn.setVisibility(View.VISIBLE);
            }

            if (strButtonText != null && !strButtonText.equals("")) {
                empty_load_btn.setText(strButtonText);
            }

            if (clickListener != null) {
                empty_load_btn.setOnClickListener(clickListener);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    protected boolean isHideTitleRightBar() {
        return true;
    }

    protected void clickTitleRight(){

    }

    protected String getTitleRightValue() {
        return "";
    }

    public void setTitleRightValue(String value) {
        tv_right.setText(value);
    }
}